<template>
  <div class="home">
    <div class="container">
      <!-- 标题区域 -->
      <div class="header">
        <h1 class="title">今天随机吃什么？</h1>
        <p class="subtitle">让我来帮你决定今天吃什么吧！</p>
      </div>
      
      <!-- 导航菜单 -->
      <div class="nav-menu">
        <el-button 
          :class="{ active: currentView === 'random' }" 
          @click="currentView = 'random'" 
          size="large"
        >
          <el-icon><Refresh /></el-icon>
          随机选择
        </el-button>
        <el-button 
          :class="{ active: currentView === 'browse' }" 
          @click="currentView = 'browse'" 
          size="large"
        >
          <el-icon><List /></el-icon>
          浏览菜品
        </el-button>
        <el-button 
          :class="{ active: currentView === 'history' }" 
          @click="currentView = 'history'" 
          size="large"
        >
          <el-icon><Clock /></el-icon>
          历史记录
        </el-button>
      </div>
      
      <!-- 随机选择区域 -->
      <div v-if="currentView === 'random'" class="random-section">
        <div class="random-button-container">
          <el-button 
            type="primary" 
            size="large" 
            class="random-button"
            @click="getRandomFood"
            :loading="randomLoading"
          >
            <el-icon><Refresh /></el-icon>
            {{ randomLoading ? '正在选择...' : '随机选择' }}
          </el-button>
        </div>
        
        <!-- 随机结果 -->
        <div v-if="randomFood" class="random-result">
          <div class="food-card">
            <div class="food-image">
              <img 
                v-if="randomFood.imageUrl" 
                :src="randomFood.imageUrl" 
                :alt="randomFood.name"
                @error="handleImageError"
              />
              <div v-else class="no-image">
                <el-icon><Food /></el-icon>
              </div>
            </div>
            
            <div class="food-info">
              <h2 class="food-name">{{ randomFood.name }}</h2>
              <p class="food-description">{{ randomFood.description }}</p>
              
              <div class="food-details">
                <div class="detail-item">
                  <el-icon><Timer /></el-icon>
                  <span>{{ randomFood.cookTime }}分钟</span>
                </div>
                <div class="detail-item">
                  <el-icon><Star /></el-icon>
                  <span>{{ getDifficultyText(randomFood.difficulty) }}</span>
                </div>
                <div v-if="randomFood.price" class="detail-item">
                  <el-icon><Money /></el-icon>
                  <span>¥{{ randomFood.price }}</span>
                </div>
              </div>
              
              <div v-if="randomFood.ingredients" class="ingredients">
                <h4>所需食材：</h4>
                <p>{{ randomFood.ingredients }}</p>
              </div>
              
              <div v-if="randomFood.steps" class="steps">
                <h4>制作步骤：</h4>
                <p class="steps-content">{{ randomFood.steps }}</p>
              </div>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button @click="getRandomFood" :loading="randomLoading">
              <el-icon><Refresh /></el-icon>
              再来一次
            </el-button>
            <el-button type="success" @click="saveToFavorites">
              <el-icon><Star /></el-icon>
              就决定是它了
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 浏览菜品区域 -->
      <div v-if="currentView === 'browse'" class="browse-section">
        <div class="filter-bar">
          <el-select 
            v-model="selectedCategory" 
            @change="filterByCategory"
            placeholder="选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
          
          <el-input
            v-model="searchKeyword"
            placeholder="搜索菜品"
            style="width: 300px; margin-left: 20px"
            @keyup.enter="searchFoods"
          >
            <template #append>
              <el-button @click="searchFoods">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        
        <div class="foods-grid" v-loading="foodsLoading">
          <div 
            v-for="food in displayFoods" 
            :key="food.id" 
            class="food-item"
            @click="selectFood(food)"
          >
            <div class="food-item-image">
              <img 
                v-if="food.imageUrl" 
                :src="food.imageUrl" 
                :alt="food.name"
                @error="handleImageError"
              />
              <div v-else class="no-image">
                <el-icon><Food /></el-icon>
              </div>
            </div>
            <div class="food-item-info">
              <h3>{{ food.name }}</h3>
              <p>{{ food.description }}</p>
              <div class="food-item-meta">
                <span>{{ food.cookTime }}分钟</span>
                <span>{{ getDifficultyText(food.difficulty) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 历史记录区域 -->
      <div v-if="currentView === 'history'" class="history-section">
        <div class="history-tabs">
          <el-button 
            :type="historyTab === 'today' ? 'primary' : 'default'"
            @click="historyTab = 'today'; loadTodayChoices()"
          >
            今日选择
          </el-button>
          <el-button 
            :type="historyTab === 'recent' ? 'primary' : 'default'"
            @click="historyTab = 'recent'; loadRecentChoices()"
          >
            最近选择
          </el-button>
          <el-button 
            :type="historyTab === 'popular' ? 'primary' : 'default'"
            @click="historyTab = 'popular'; loadPopularFoods()"
          >
            热门菜品
          </el-button>
        </div>
        
        <div class="history-content" v-loading="historyLoading">
          <div v-if="historyTab === 'today' || historyTab === 'recent'" class="choice-list">
            <div 
              v-for="choice in historyChoices" 
              :key="choice.id" 
              class="choice-item"
            >
              <div class="choice-info">
                <h4>{{ choice.foodName }}</h4>
                <p>{{ formatTime(choice.createTime) }}</p>
              </div>
            </div>
          </div>
          
          <div v-if="historyTab === 'popular'" class="popular-list">
            <div 
              v-for="(food, index) in popularFoods" 
              :key="food.id" 
              class="popular-item"
            >
              <div class="rank">{{ index + 1 }}</div>
              <div class="popular-info">
                <h4>{{ food.name }}</h4>
                <p>被选择了 {{ food.choice_count }} 次</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getRandomFood as getRandomFoodApi, getAllEnabledFoods, getFoodsByCategory, searchFoods as searchFoodsApi } from '../api/food'
import { getEnabledCategories } from '../api/category'
import { getRecentChoices, getTodayChoices, getPopularFoods } from '../api/history'
import { ElMessage } from 'element-plus'

export default {
  name: 'Home',
  setup() {
    const currentView = ref('random')
    const randomFood = ref(null)
    const randomLoading = ref(false)
    
    // 浏览相关
    const categories = ref([])
    const allFoods = ref([])
    const displayFoods = ref([])
    const selectedCategory = ref(null)
    const searchKeyword = ref('')
    const foodsLoading = ref(false)
    
    // 历史记录相关
    const historyTab = ref('today')
    const historyChoices = ref([])
    const popularFoods = ref([])
    const historyLoading = ref(false)
    
    const getRandomFood = async () => {
      randomLoading.value = true
      try {
        const res = await getRandomFoodApi()
        randomFood.value = res.data
        ElMessage.success('为您推荐了一道美食！')
      } catch (error) {
        ElMessage.error('获取随机菜品失败')
      } finally {
        randomLoading.value = false
      }
    }
    
    const loadCategories = async () => {
      try {
        const res = await getEnabledCategories()
        categories.value = res.data
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    }
    
    const loadAllFoods = async () => {
      foodsLoading.value = true
      try {
        const res = await getAllEnabledFoods()
        allFoods.value = res.data
        displayFoods.value = res.data
      } catch (error) {
        ElMessage.error('加载菜品失败')
      } finally {
        foodsLoading.value = false
      }
    }
    
    const filterByCategory = async () => {
      if (!selectedCategory.value) {
        displayFoods.value = allFoods.value
        return
      }
      
      foodsLoading.value = true
      try {
        const res = await getFoodsByCategory(selectedCategory.value)
        displayFoods.value = res.data
      } catch (error) {
        ElMessage.error('筛选失败')
      } finally {
        foodsLoading.value = false
      }
    }
    
    const searchFoods = async () => {
      if (!searchKeyword.value.trim()) {
        displayFoods.value = allFoods.value
        return
      }
      
      foodsLoading.value = true
      try {
        const res = await searchFoodsApi(searchKeyword.value)
        displayFoods.value = res.data
      } catch (error) {
        ElMessage.error('搜索失败')
      } finally {
        foodsLoading.value = false
      }
    }
    
    const selectFood = (food) => {
      randomFood.value = food
      currentView.value = 'random'
      ElMessage.success(`选择了：${food.name}`)
    }
    
    const loadTodayChoices = async () => {
      historyLoading.value = true
      try {
        const res = await getTodayChoices()
        historyChoices.value = res.data
      } catch (error) {
        ElMessage.error('加载今日选择失败')
      } finally {
        historyLoading.value = false
      }
    }
    
    const loadRecentChoices = async () => {
      historyLoading.value = true
      try {
        const res = await getRecentChoices()
        historyChoices.value = res.data
      } catch (error) {
        ElMessage.error('加载最近选择失败')
      } finally {
        historyLoading.value = false
      }
    }
    
    const loadPopularFoods = async () => {
      historyLoading.value = true
      try {
        const res = await getPopularFoods(7)
        popularFoods.value = res.data
      } catch (error) {
        ElMessage.error('加载热门菜品失败')
      } finally {
        historyLoading.value = false
      }
    }
    
    const saveToFavorites = () => {
      ElMessage.success('已记录您的选择！')
    }
    
    const getDifficultyText = (difficulty) => {
      const textMap = { 1: '简单', 2: '中等', 3: '困难' }
      return textMap[difficulty] || '未知'
    }
    
    const handleImageError = (e) => {
      e.target.style.display = 'none'
    }
    
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      return new Date(timeStr).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      loadCategories()
      loadAllFoods()
      loadTodayChoices()
    })
    
    return {
      currentView,
      randomFood,
      randomLoading,
      categories,
      displayFoods,
      selectedCategory,
      searchKeyword,
      foodsLoading,
      historyTab,
      historyChoices,
      popularFoods,
      historyLoading,
      getRandomFood,
      filterByCategory,
      searchFoods,
      selectFood,
      loadTodayChoices,
      loadRecentChoices,
      loadPopularFoods,
      saveToFavorites,
      getDifficultyText,
      handleImageError,
      formatTime
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

/* 标题区域 */
.header {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.title {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.subtitle {
  font-size: 18px;
  opacity: 0.9;
}

/* 导航菜单 */
.nav-menu {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 40px;
}

.nav-menu .el-button {
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.nav-menu .el-button:hover,
.nav-menu .el-button.active {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
}

/* 随机选择区域 */
.random-section {
  text-align: center;
}

.random-button-container {
  margin-bottom: 40px;
}

.random-button {
  font-size: 20px;
  padding: 15px 40px;
  border-radius: 50px;
  background: linear-gradient(45deg, #ff6b6b, #ffa500);
  border: none;
  color: white;
  font-weight: bold;
  box-shadow: 0 8px 20px rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
}

.random-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(255, 107, 107, 0.4);
}

/* 随机结果卡片 */
.random-result {
  margin-top: 40px;
}

.food-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  display: flex;
  gap: 30px;
  align-items: flex-start;
  text-align: left;
  margin-bottom: 30px;
}

.food-image {
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  border-radius: 15px;
  overflow: hidden;
  background: #f5f5f5;
}

.food-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 60px;
  color: #ccc;
}

.food-info {
  flex: 1;
}

.food-name {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.food-description {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.food-details {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 5px;
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 14px;
  color: #555;
}

.ingredients, .steps {
  margin-top: 20px;
}

.ingredients h4, .steps h4 {
  color: #333;
  margin-bottom: 8px;
  font-size: 16px;
}

.ingredients p, .steps p {
  color: #666;
  line-height: 1.6;
}

.steps-content {
  white-space: pre-line;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 浏览区域 */
.browse-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  backdrop-filter: blur(10px);
}

.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.foods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.food-item {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.food-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.food-item-image {
  height: 200px;
  overflow: hidden;
}

.food-item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.food-item-info {
  padding: 20px;
}

.food-item-info h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.food-item-info p {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.food-item-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #999;
}

/* 历史记录区域 */
.history-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  backdrop-filter: blur(10px);
}

.history-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.choice-list, .popular-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.choice-item, .popular-item {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.rank {
  width: 40px;
  height: 40px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.choice-info h4, .popular-info h4 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.choice-info p, .popular-info p {
  font-size: 14px;
  color: #666;
}

@media (max-width: 768px) {
  .title {
    font-size: 32px;
  }
  
  .nav-menu {
    flex-direction: column;
    align-items: center;
  }
  
  .food-card {
    flex-direction: column;
    text-align: center;
  }
  
  .food-image {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }
  
  .foods-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .filter-bar .el-select,
  .filter-bar .el-input {
    width: 100% !important;
    margin-left: 0 !important;
  }
}
</style>